package com.dev.security.shiro;

import com.dev.security.util.ResponseUtil;
import com.dev.security.vo.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录过滤器
 *
 * @author yuboon
 * @version v1.0
 * @date 2020/04/12
 */
@Slf4j
public class LoginFilter extends FormAuthenticationFilter {

    /**
     * 认证失败
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        boolean isAjaxRequest = isAjaxRequest(req);

        if (isAjaxRequest) {
            log.info(req.getRequestURI() + " isAjax 请求");
            ResponseData responseData = new ResponseData();
            responseData.setCode(100);
            responseData.setMessage("登录认证失败");
            // 信息写到前台
            ResponseUtil.writeJson(resp,responseData);
        } else {
            // 重定向的登录
            saveRequestAndRedirectToLogin(request, response);
        }

        return false;
    }


    /***
     * 判断一个请求是否为AJAX请求,是则返回true
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        //如果requestType能拿到值，并且值为 XMLHttpRequest ,表示客户端的请求为异步请求，那自然是ajax请求了，反之如果为null,则是普通的请求
        if(requestType == null){
            return false;
        }
        return true;
    }

}
